﻿package com.dao;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.dao.DBConnection;

public abstract class BaseDao {

	protected Connection conn;
	protected PreparedStatement stmt;
	protected ResultSet rst;
	protected CallableStatement calltmt;
	
	
	protected final void getConnection() throws SQLException {
		conn = DBConnection.getConnection();
	}
	
	
	
	protected final void closeAll() {
		if (rst != null) {
			try {
				rst.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				rst = null;
			}
		}
		if (stmt != null) {
			try {
				stmt.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				stmt = null;
			}
		}
		if (stmt != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				conn = null;
			}
		}
	}
	
	protected final int executeSQL(String sql,List params){
		int count = 0;
		try {
			this.getConnection();
			stmt = this.conn.prepareStatement(sql);
			setPreparedStatement(params);
			count = stmt.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			this.closeAll();
		}
		return count;	
	}
	public void setPreparedStatement(List params) throws SQLException {
		if (params != null && params.size() > 0) {
			for (int i = 0; i < params.size(); i++) {
				stmt.setObject(i + 1, params.get(i));
			}
		}
	}
	
	public List findAll(String sql,Object clas) {
		List pslist = null;
		try {
			this.getConnection();
			stmt= conn.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
			ResultSet rs = stmt.executeQuery();
			
			pslist = fetchMultiResults(rs,clas);
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally {
			this.closeAll();
		}
		return pslist;
	}

	protected abstract List fetchMultiResults(ResultSet rs,Object clas)throws SQLException;
}
